import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, Form, Card, Space, Tag, Popconfirm, message, Row, Col } from 'antd';
import { PlusOutlined, SearchOutlined, DeleteOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import EquipmentAddDrawer from './EquipmentAddDrawer';
import EquipmentEditDrawer from './EquipmentEditDrawer';
import EquipmentViewDrawer from './EquipmentViewDrawer';

const { Option } = Select;

interface EquipmentItem {
  id: string;
  name: string;
  externalId: string;
  categoryName: string;
  dockingBrandName: string;
  areaName: string;
  status: 'ONLINE' | 'OFFLINE' | 'FAILURE';
  updateTime: string;
  updateByUserName: string;
}

interface SearchForm {
  deviceName: string;
  externalId: string;
  deviceRunningStatus: string;
}

const EquipmentList: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<EquipmentItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [, setSearchForm] = useState<SearchForm>({
    deviceName: '',
    externalId: '',
    deviceRunningStatus: '',
  });
  const [addDrawerVisible, setAddDrawerVisible] = useState(false);
  const [editDrawerVisible, setEditDrawerVisible] = useState(false);
  const [viewDrawerVisible, setViewDrawerVisible] = useState(false);
  const [currentEquipment, setCurrentEquipment] = useState<EquipmentItem | null>(null);

  // 模拟数据
  const mockData: EquipmentItem[] = [
    {
      id: '1',
      name: '摄像头-01',
      externalId: 'CAM001',
      categoryName: '视频监控',
      dockingBrandName: '海康威视',
      areaName: 'A区',
      status: 'ONLINE',
      updateTime: '2024-01-15 10:30:00',
      updateByUserName: '管理员',
    },
    {
      id: '2',
      name: '温度传感器-02',
      externalId: 'TEMP002',
      categoryName: '环境监测',
      dockingBrandName: '西门子',
      areaName: 'B区',
      status: 'OFFLINE',
      updateTime: '2024-01-14 15:45:00',
      updateByUserName: '操作员',
    },
    {
      id: '3',
      name: '门禁控制器-03',
      externalId: 'DOOR003',
      categoryName: '门禁系统',
      dockingBrandName: '达实',
      areaName: 'C区',
      status: 'FAILURE',
      updateTime: '2024-01-13 09:20:00',
      updateByUserName: '维修员',
    },
  ];

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      setData(mockData);
      setLoading(false);
    }, 500);
  };

  const handleSearch = () => {
    const formValues = form.getFieldsValue();
    setSearchForm(formValues);
    
    // 模拟搜索过滤
    const filteredData = mockData.filter(item => {
      const matchName = !formValues.deviceName || item.name.includes(formValues.deviceName);
      const matchId = !formValues.externalId || item.externalId.includes(formValues.externalId);
      const matchStatus = !formValues.deviceRunningStatus || item.status === formValues.deviceRunningStatus;
      return matchName && matchId && matchStatus;
    });
    
    setData(filteredData);
  };

  const handleReset = () => {
    form.resetFields();
    setSearchForm({
      deviceName: '',
      externalId: '',
      deviceRunningStatus: '',
    });
    setData(mockData);
  };

  const handleAdd = () => {
    setAddDrawerVisible(true);
  };

  const handleAddSubmit = (values: any) => {
    const newEquipment: EquipmentItem = {
      id: Date.now().toString(),
      name: values.name,
      externalId: values.externalId,
      categoryName: '新建设备',
      dockingBrandName: '未知品牌',
      areaName: values.areaId ? values.areaId.join('-') : '未指定区域',
      status: 'ONLINE',
      updateTime: new Date().toLocaleString('zh-CN'),
      updateByUserName: '当前用户',
    };
    
    setData([...data, newEquipment]);
    setAddDrawerVisible(false);
    message.success('设备新增成功');
  };

  const handleAddClose = () => {
    setAddDrawerVisible(false);
  };

  const handleEditSubmit = (values: any) => {
    if (currentEquipment) {
      const updatedData = data.map(item => 
        item.id === currentEquipment.id 
          ? { ...item, ...values, updateTime: new Date().toLocaleString('zh-CN') }
          : item
      );
      setData(updatedData);
      setEditDrawerVisible(false);
      setCurrentEquipment(null);
      message.success('设备编辑成功');
    }
  };

  const handleEditClose = () => {
    setEditDrawerVisible(false);
    setCurrentEquipment(null);
  };

  const handleViewClose = () => {
    setViewDrawerVisible(false);
    setCurrentEquipment(null);
  };

  const handleView = (record: EquipmentItem) => {
    setCurrentEquipment(record);
    setViewDrawerVisible(true);
  };

  const handleEdit = (record: EquipmentItem) => {
    setCurrentEquipment(record);
    setEditDrawerVisible(true);
  };

  const handleDelete = (record: EquipmentItem) => {
    message.success(`删除设备: ${record.name}`);
    setData(data.filter(item => item.id !== record.id));
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的设备');
      return;
    }
    setData(data.filter(item => !selectedRowKeys.includes(item.id)));
    message.success(`批量删除 ${selectedRowKeys.length} 个设备成功`);
    setSelectedRowKeys([]);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'ONLINE': return 'success';
      case 'OFFLINE': return 'default';
      case 'FAILURE': return 'error';
      default: return 'default';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'ONLINE': return '正常';
      case 'OFFLINE': return '离线';
      case 'FAILURE': return '故障';
      default: return status;
    }
  };

  const columns: ColumnsType<EquipmentItem> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_, __, index) => index + 1,
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '设备编号',
      dataIndex: 'externalId',
      key: 'externalId',
      width: 200,
    },
    {
      title: '设备分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 150,
    },
    {
      title: '设备品牌',
      dataIndex: 'dockingBrandName',
      key: 'dockingBrandName',
      width: 150,
    },
    {
      title: '安装区域',
      dataIndex: 'areaName',
      key: 'areaName',
      width: 150,
    },
    {
      title: '运行状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 160,
    },
    {
      title: '编辑人员',
      dataIndex: 'updateByUserName',
      key: 'updateByUserName',
      width: 100,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除吗?"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  return (
    <div className="equipment-list">
      <Card>
        <Form
          form={form}
          layout="inline"
          style={{ marginBottom: 16 }}
        >
          <Row gutter={16} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item
                label="设备名称"
                name="deviceName"
                style={{ marginBottom: 16 }}
              >
                <Input
                  placeholder="请输入设备名称"
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                label="设备编号"
                name="externalId"
                style={{ marginBottom: 16 }}
              >
                <Input
                  placeholder="请输入设备编号"
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                label="运行状态"
                name="deviceRunningStatus"
                style={{ marginBottom: 16 }}
              >
                <Select
                  placeholder="请选择运行状态"
                  allowClear
                  style={{ width: '100%' }}
                >
                  <Option value="ONLINE">正常</Option>
                  <Option value="OFFLINE">离线</Option>
                  <Option value="FAILURE">故障</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item style={{ marginBottom: 16 }}>
                <Space>
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    onClick={handleSearch}
                  >
                    搜索
                  </Button>
                  <Button onClick={handleReset}>重置</Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              新增设备
            </Button>
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={handleBatchDelete}
              disabled={selectedRowKeys.length === 0}
            >
              批量删除
            </Button>
          </Space>
        </div>

        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={data}
          rowSelection={rowSelection}
          pagination={{
            total: data.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          scroll={{ x: 1300 }}
        />
      </Card>
      
      <EquipmentAddDrawer
        open={addDrawerVisible}
        onClose={handleAddClose}
        onSubmit={handleAddSubmit}
      />
      
      <EquipmentEditDrawer
        open={editDrawerVisible}
        onClose={handleEditClose}
        onSubmit={handleEditSubmit}
        equipment={currentEquipment}
      />
      
      <EquipmentViewDrawer
        open={viewDrawerVisible}
        onClose={handleViewClose}
        equipment={currentEquipment}
      />
    </div>
  );
};

export default EquipmentList;